package com.fastjars.business.upload.hunter;

import com.fastjars.business.upload.ActionHandler;
import com.fastjars.business.upload.ActionResult;
import com.fastjars.business.upload.ActionState;
import com.fastjars.business.upload.PathFormat;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;

/**
 * FileManager
 *
 * @author Brant Liu <br> 邮箱：<br>lbf1988@qq.com <br>日期：<br>2018/04/17
 * @version 1.0.0
 */
public class FileManager {
    private String dir = null;
    private String rootPath = null;
    private String[] allowFiles = null;
    private int count = 0;

    public FileManager(Map<String, Object> conf) {
        this.rootPath = (String) conf.get("rootPath");
        this.dir = this.rootPath + (String) conf.get("dir");
        this.allowFiles = this.getAllowFiles(conf.get("allowFiles"));
        this.count = (Integer) conf.get("count");
    }

    public ActionResult listFile(int index) {
        File dir = new File(this.dir);
        ActionResult state = null;
        if (!dir.exists()) {
            return new ActionResult(ActionState.NOT_EXIST);
        }
        if (!dir.isDirectory()) {
            return new ActionResult(ActionState.NOT_DIRECTORY);
        }
        Collection<File> list = FileUtils.listFiles(dir, this.allowFiles, true);
        if (index < 0 || index > list.size()) {
            state = new ActionResult(ActionState.SUCCESS);
        } else {
            Object[] fileList = Arrays.copyOfRange(list.toArray(), index, index + this.count);
            state = this.getState(fileList);
        }
        state.setStart(index);
        state.setTotal(list.size());
        return state;
    }

    private ActionResult getState(Object[] files) {
        ActionResult state = new ActionResult(ActionState.SUCCESS);
        ActionResult fileState = null;
        File file = null;
        for (Object obj : files) {
            if (obj == null) {
                break;
            }
            file = (File) obj;
            fileState = new ActionResult(ActionState.SUCCESS);
            fileState.setUrl(PathFormat.format(this.getPath(file)));
            state.addItem(fileState);
        }
        return state;
    }

    private String getPath(File file) {
        String path = PathFormat.format(file.getAbsolutePath());
        path = path.replace(this.rootPath, ActionHandler.FILE_SEPARATOR);
        path = path.replace("//", ActionHandler.FILE_SEPARATOR);
        return path;
    }

    private String[] getAllowFiles(Object fileExt) {
        String[] exts = null;
        String ext = null;
        if (fileExt == null) {
            return new String[0];
        }
        exts = (String[]) fileExt;
        for (int i = 0, len = exts.length; i < len; i++) {
            ext = exts[i];
            exts[i] = ext.replace(".", "");
        }
        return exts;
    }
}
